/* eslint-disable array-callback-return */
import React, { Component, Fragment } from 'react';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Spin, Row, Col, Input, Button, Radio, Select, Cascader } from 'antd';

import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import queryString from 'query-string';
import router from 'umi/router';
import SelectTitleAddr from './SelectTitleAddr';
import styles from './center.less';
import FooterToolbar from '@/components/FooterToolbar';

const { Option } = Select;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
@connect(({ costcenter, publicdata, loading }) => ({
  costcenter,
  dictCode: publicdata.dictCode,
  selectTitleLoading: loading.effects['costcenter/getAreaList'],
  loading: loading.models.costcenter,
  submitLoading:
    loading.effects['costcenter/submit'] || loading.effects['costcenter/updateInvRuleCost'],
}))
@Form.create()
class CostCenter extends Component {
  state = {
    provCityAreaList: [],
  };

  tableSearchLayout = {
    labelCol: { md: { span: 9 } },
    wrapperCol: { md: { span: 15 } },
  };

  formLayout = {
    labelCol: { md: { span: 12 } },
    wrapperCol: { md: { span: 12 } },
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const { invRuleId } = queryString.parse(location.search);
    const custId = queryString.parse(location.search).custSuppId;
    const { costId } = queryString.parse(location.search);
    this.setState({
      invRuleId,
      costId,
    });
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['FM_INV_RULE_WAY', 'FM_INV_RULE_TYPE'],
    });

    this.getAreaList(null, data => {
      data.map(item => {
        const temp = item;
        temp.label = item.areaName;
        temp.value = item.areaId;
        temp.isLeaf = false;
      });
      this.setState({ provCityAreaList: data });
    });
    // 获取抬头和地址列表
    dispatch({
      type: 'costcenter/fetchCenterList',
      payload: {
        custId,
      },
    });
    if (costId) {
      dispatch({
        type: 'costcenter/fetchCostDetail',
        payload: {
          costId,
          invRuleId,
        },
      }).then(res => {
        const { invRulePanyTermMailDto } = res;
        invRulePanyTermMailDto.forEach(item => {
          const temp = item;
          temp.id = 0;
          item.invMailList.forEach(items => {
            const temps = items;
            const areaList = [];
            items.areaList.forEach(values => {
              areaList.push(values.areaId);
            });

            temps.mailArea = areaList;
            if (areaList.length) {
              this.getProvCityAreaList(areaList, () => {
                dispatch({
                  type: 'costcenter/updateModelData',
                  payload: {
                    invRulePanyTermMailDto,
                  },
                });
              });
            } else {
              dispatch({
                type: 'costcenter/updateModelData',
                payload: {
                  invRulePanyTermMailDto,
                },
              });
            }
          });
        });
      });
    } else {
      // 获取发票规则列表
      dispatch({
        type: 'costcenter/fetchRuleList',
        payload: {
          invRuleId,
        },
      });
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'costcenter/updateModelData',
      payload: {
        invRulePanyTermMailDto: [
          {
            id: 0,
            costId: '',
            invCompany: {},
            invMailList: [{ costInvType: 1, invPay: 1 }],
          },
        ],
        invRulePanyItem: [
          {
            id: 0,
            costId: '',
            invCompany: {},
            invMailList: [],
          },
        ],
        id: 0,
        // 发票信息集合
        dtoId: '0',
        costInvType: 1,
        centerList: [],
        custCostCenterList: [], // 成本中心下拉列表
        invoiceList: [],
        mailAddrList: [],
        titleAddrData: [],
        titleListData: [],

        titleModalVisible: false,
        addrModalVisible: false,
        titleAddrType: '1',
        costInvTypeId: 1,
      },
    });
  }

  addInvInfo = () => {
    const {
      costcenter: { invRulePanyTermMailDto, id, invRulePanyItem },
      dispatch,
    } = this.props;

    dispatch({
      type: 'costcenter/updateModelData',
      payload: {
        id: id + 1,
      },
    });
    invRulePanyTermMailDto.push({ ...invRulePanyItem[0], id: id + 1 });
    dispatch({
      type: 'costcenter/updateModelData',
      payload: { invRulePanyTermMailDto },
    });
  };

  handleModalVisible = () => {
    const {
      costcenter: { modalVisible },
      dispatch,
    } = this.props;
    dispatch({
      type: 'costcenter/updateModelData',
      payload: { modalVisible: !modalVisible },
    });
  };

  selTitleAddr = (id, type, costInvType) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'costcenter/updateModelData',
      payload: {
        dtoId: id,
        titleAddrType: type,
        costInvTypeId: costInvType,
      },
    });
    this.handleModalVisible(true);
  };

  // 选择发票交付方式
  radioChange = (id, costInvType, e) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'costcenter/invPayChange',
      payload: {
        dtoId: id,
        costInvTypeId: costInvType, // 区分哪一项
        invPay: e.target.value,
      },
    });
  };

  saveTitleInfo = (dtoId, titleAddrType, info) => {
    const {
      form,
      costcenter: { costInvTypeId },
    } = this.props;

    const { invRulePanyTermMailDto } = form.getFieldsValue();
    if (+titleAddrType === 1) {
      Object.keys(invRulePanyTermMailDto[dtoId].invCompany).forEach(key => {
        form.setFieldsValue({
          [`invRulePanyTermMailDto[${dtoId}][invCompany][${key}]`]: info[key],
        });
      });
    } else if (invRulePanyTermMailDto[dtoId].invMailList.length > 0) {
      Object.keys(invRulePanyTermMailDto[dtoId].invMailList[costInvTypeId]).forEach(key => {
        if (key !== 'costInvType' || key !== 'invPay')
          form.setFieldsValue({
            [`invRulePanyTermMailDto[${dtoId}][invMailList][${costInvTypeId}][${key}]`]: info[key],
          });
      });
    }
  };

  // 发票和地址弹窗保存方法
  saveTitleOrAddr = values => {
    const {
      costcenter: { titleAddrType, dtoId },
    } = this.props;
    if (titleAddrType === '1') {
      this.saveTitleInfo(dtoId, titleAddrType, values[0]);
    } else {
      const mailArea = []; // 地址回显数据
      values[0].areaList.forEach(item => {
        mailArea.push(item.areaId);
      });
      this.getProvCityAreaList(
        mailArea,
        this.saveTitleInfo(dtoId, titleAddrType, { ...values[0], mailArea })
      );
    }
  };

  // 动态加载
  loadAreaData = selectedOptions => {
    const { provCityAreaList } = this.state;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    const parentId = selectedOptions[selectedOptions.length - 1].value;
    targetOption.loading = true;
    const childrenData = [];
    this.getAreaList(parentId, data => {
      data.map(item => {
        const temp = item;
        temp.isLeaf = item.areaNature === 6;
        temp.label = item.areaName;
        temp.value = item.areaId;
        childrenData.push(item);
      });
    });
    // load options lazily
    setTimeout(() => {
      targetOption.loading = false;
      targetOption.children = childrenData;
      this.setState({
        provCityAreaList: [...provCityAreaList],
      });
    }, 1000);
  };

  // 查询省市区
  getAreaList = (areaId, callback) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'custedit/getAreaList',
      payload: {
        parentId: areaId,
      },
    }).then(res => {
      callback(res.data);
    });
  };

  // 获取省市区回显
  getProvCityAreaList = (areaIdList, callback) => {
    const { provCityAreaList } = this.state;
    const cityData = [];
    const countyData = [];
    switch (areaIdList.length) {
      case 1:
        if (callback) callback();
        break;
      case 2:
        this.getAreaList(areaIdList[0], data => {
          data.map(area => {
            cityData.push({
              label: area.areaName,
              value: area.areaId,
              isLeaf: area.areaNature === 6,
            });
          });
          provCityAreaList.map(p => {
            const temp = p;
            if (p.areaId === areaIdList[0]) {
              temp.children = cityData;
            }
          });
          this.setState({ provCityAreaList }, () => {
            if (callback) callback();
          });
        });
        break;
      case 3:
        // 获取市
        this.getAreaList(areaIdList[0], data => {
          data.map(area => {
            cityData.push({
              label: area.areaName,
              value: area.areaId,
              isLeaf: area.areaNature === 6,
            });
          });
          provCityAreaList.map(p => {
            const temp = p;
            if (p.areaId === areaIdList[0]) {
              temp.children = cityData;
            }
          });

          // 获取区县
          this.getAreaList(areaIdList[1], datas => {
            datas.map(area => {
              countyData.push({
                label: area.areaName,
                value: area.areaId,
                isLeaf: area.areaNature === 6,
              });
            });
            provCityAreaList.map(p => {
              if (p.areaId === areaIdList[0]) {
                // 判断省
                p.children.map(c => {
                  if (c.value === areaIdList[1]) {
                    // 判读市
                    const temp = c;
                    temp.children = countyData;
                  }
                });
              }
            });
            this.setState({ provCityAreaList }, () => {
              if (callback) callback();
            });
          });
        });
        break;
      default:
        break;
    }
  };

  // 地区选择：省市区
  selectProvCityArea = (value, selectedOptions, id, costInvType) => {
    const { dispatch } = this.props;
    if (value.length > 3) {
      dispatch({
        type: 'costcenter/setMailArea',
        payload: {
          mailArea: value,
          dtoId: id,
          costInvType,
        },
      });
    }
  };

  // 提交
  submit = () => {
    const { form, dispatch } = this.props;
    const { costId, invRuleId } = this.state;
    form.validateFieldsAndScroll({ force: true }, (err, values) => {
      if (!err) {
        const { invRulePanyTermMailDto } = values;
        const arr = [];

        // 过滤invMailListList form表单值
        Object.entries(invRulePanyTermMailDto).forEach(item => {
          const temp = item;
          const arr2 = [];
          Object.entries(item[1].invMailList).forEach(items => {
            arr2.push(items[1]);
          });
          temp[1].invMailList = arr2;
          arr.push(item[1]);
        });
        // 修改邮寄地址入参格式
        arr.forEach(item => {
          item.invMailList.forEach(items => {
            const newItems = items;
            if (items.mailArea && items.mailArea[2]) {
              const temp = items.mailArea[2];
              newItems.mailArea = temp;
            }
          });
        });
        if (costId) {
          dispatch({
            type: 'costcenter/updateInvRuleCost',
            payload: {
              invRulePanyTermMailDto: arr,
              invRuleId,
              costId,
            },
          });
        } else {
          dispatch({
            type: 'costcenter/submit',
            payload: {
              invRulePanyTermMailDto: arr,
              invRuleId,
            },
          });
        }
      }
    });
  };

  cancel = () => {
    router.goBack();
  };

  // 删除某一项
  delList = id => {
    const {
      dispatch,
      costcenter: { invRulePanyTermMailDto },
    } = this.props;
    dispatch({
      type: 'costcenter/updateModelData',
      payload: {
        invRulePanyTermMailDto: invRulePanyTermMailDto.filter(item => item.id !== id),
      },
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      costcenter: {
        invRulePanyTermMailDto,
        custCostCenterList,
        invoiceList,
        mailAddrList,
        selectTitleLoading,
        titleAddrType,
        modalVisible,
      },
      dictCode: { FM_INV_RULE_WAY = [] },
      loading,
      submitLoading,
    } = this.props;
    const { provCityAreaList, costId } = this.state;
    const renderInvType = (id, invMailList) =>
      // 电子普票
      invMailList.map(item => {
        if (+item.costInvType !== 2) {
          return (
            <Fragment key={item.costInvType}>
              <Row>
                <Col md={8} sm={24}>
                  <FormItem label="发票类型" {...this.tableSearchLayout} className={styles.pdSet}>
                    {getFieldDecorator(
                      `invRulePanyTermMailDto[${id}][invMailList][${item.costInvType}]costInvType`,
                      {
                        rules: [{ required: false }],
                        initialValue: item.costInvType,
                      }
                    )(<span style={{ width: '100%' }}>{item.costInvTypeName}</span>)}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <FormItem label="发票交付方式" {...this.tableSearchLayout} className={styles.pdSet}>
                    {getFieldDecorator(
                      `invRulePanyTermMailDto[${id}][invMailList][${item.costInvType}]invPay`,
                      {
                        rules: [{ required: true, message: '请选择发票交付方式' }],
                        initialValue: `${item.invPay}`,
                      }
                    )(
                      <RadioGroup onChange={value => this.radioChange(id, item.costInvType, value)}>
                        {FM_INV_RULE_WAY.filter(items => items.itemName !== '邮件')
                          .sort((a, b) => b.itemCode - a.itemCode)
                          .map(options => (
                            <Radio value={options.itemCode} key={options.itemCode}>
                              {options.itemName}
                            </Radio>
                          ))}
                      </RadioGroup>
                    )}
                    {+item.invPay === 1 && (
                      <a onClick={() => this.selTitleAddr(id, '2', item.costInvType)}>选择地址</a>
                    )}
                  </FormItem>
                </Col>
              </Row>
              {+item.invPay === 1 && (
                <Fragment>
                  <Row>
                    <Col md={8} sm={24}>
                      <FormItem label="联系人姓名" {...this.tableSearchLayout}>
                        {getFieldDecorator(
                          `invRulePanyTermMailDto[${id}][invMailList][${
                            item.costInvType
                          }][contPerName]`,
                          {
                            initialValue: item.contPerName,
                            rules: [
                              {
                                required: true,
                                message: '请输入的内容必须在1-30个字',
                                pattern: /^[A-Za-z\u4e00-\u9fa5\0-9]{1,30}$/,
                              },
                            ],
                          }
                        )(<Input placeholder="请输入联系人姓名" maxLength={30} />)}
                      </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                      <FormItem label="联系人电话" {...this.tableSearchLayout}>
                        {getFieldDecorator(
                          `invRulePanyTermMailDto[${id}][invMailList][${
                            item.costInvType
                          }][contPerPhone]`,
                          {
                            initialValue: item.contPerPhone,
                            rules: [
                              {
                                required: true,
                                message: '请正确输入手机号码或固话(限制12位)',
                                pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,12}$/,
                              },
                            ],
                          }
                        )(<Input placeholder="请输入联系人电话" maxLength={12} />)}
                      </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                      <FormItem label="邮寄地址" {...this.tableSearchLayout}>
                        {getFieldDecorator(
                          `invRulePanyTermMailDto[${id}][invMailList][${
                            item.costInvType
                          }][mailArea]`,
                          {
                            rules: [
                              {
                                type: 'array',
                                required: true,
                                message: '请选择(市区或县级)',
                                min: 2,
                              },
                            ],
                            initialValue: item.mailArea,
                          }
                        )(
                          <Cascader
                            placeholder="请选择"
                            options={provCityAreaList}
                            loadData={this.loadAreaData}
                            onChange={(value, selectedOptions) =>
                              this.selectProvCityArea(value, selectedOptions, id, item.costInvType)
                            }
                            changeOnSelect
                          />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col md={8} sm={24}>
                      <FormItem label="详细地址" {...this.tableSearchLayout}>
                        {getFieldDecorator(
                          `invRulePanyTermMailDto[${id}][invMailList][${
                            item.costInvType
                          }][mailAddr]`,
                          {
                            initialValue: item.mailAddr,
                            rules: [{ required: true, message: '请输入的内容必须在1-100个字' }],
                          }
                        )(<Input placeholder="请输入详细地址" maxLength={100} />)}
                      </FormItem>
                    </Col>
                  </Row>
                </Fragment>
              )}
            </Fragment>
          );
        }
        return (
          <Row>
            <Col md={8} sm={24}>
              <FormItem label="发票类型" {...this.tableSearchLayout} className={styles.pdSet}>
                {getFieldDecorator(
                  `invRulePanyTermMailDto[${id}][invMailList][${item.costInvType}][costInvType]`,
                  {
                    rules: [{ required: false, message: '请输入发票类型' }],
                    initialValue: item.costInvType,
                  }
                )(<span style={{ width: '100%' }}>{item.costInvTypeName}</span>)}
              </FormItem>
            </Col>
            <Col md={8} sm={24}>
              <FormItem label="普票交互方式" {...this.tableSearchLayout} className={styles.pdSet}>
                {getFieldDecorator(
                  `invRulePanyTermMailDto[${id}][invMailList][${item.costInvType}][invPay]`,
                  {
                    rules: [{ required: false }],
                    initialValue: `${item.invPay}`,
                  }
                )(<span style={{ width: '100%' }}>{item.invPayName}</span>)}
              </FormItem>
            </Col>
            <Col md={8} sm={24}>
              <FormItem label="邮箱地址" {...this.tableSearchLayout}>
                {getFieldDecorator(
                  `invRulePanyTermMailDto[${id}][invMailList][${item.costInvType}][email]`,
                  {
                    initialValue: item.email,
                    rules: [
                      {
                        type: 'email',
                        required: true,
                        message: '应为邮箱格式且长度不能超过50',
                        pattern: /^[A-Za-z\u4e00-\u9fa5\0-9]{1,50}$/,
                      },
                    ],
                  }
                )(<Input placeholder="请输入邮箱地址" maxLength={50} />)}
              </FormItem>
            </Col>
          </Row>
        );
      });
    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading || false}>
          <div className={styles.cardContainer}>
            <Form>
              <div>
                {invRulePanyTermMailDto.map(item => (
                  <div key={item.id} style={{ marginBottom: 20, background: '#fff' }}>
                    <Card
                      title="发票抬头"
                      extra={
                        invRulePanyTermMailDto.length > 1 ? (
                          <DeleteOutlined className="dynamic-delete-button" onClick={() => this.delList(item.id)} />
                        ) : null
                      }
                    >
                      <Row>
                        <Col md={8} sm={24}>
                          <FormItem label="成本中心" {...this.tableSearchLayout}>
                            {getFieldDecorator(`invRulePanyTermMailDto[${item.id}][costId]`, {
                              initialValue: item.costId || undefined,
                              rules: [{ required: true, message: '请选择成本中心' }],
                            })(
                              <Select
                                placeholder="请选择成本中心"
                                allowClear
                                showSearch
                                optionFilterProp="children"
                                disabled={!!costId}
                              >
                                {custCostCenterList.map(items => (
                                  <Option key={items.costCenterId}>{items.name}</Option>
                                ))}
                              </Select>
                            )}
                          </FormItem>
                        </Col>
                        <Col md={8} sm={24}>
                          <FormItem
                            className={styles.labelContent}
                            label={<a onClick={() => this.selTitleAddr(item.id, '1')}>选择抬头</a>}
                            {...this.tableSearchLayout}
                          />
                        </Col>
                      </Row>
                      <Row>
                        <Col md={8} sm={24}>
                          <FormItem label="单位名称" {...this.tableSearchLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][holderName]`,
                              {
                                initialValue: item.invCompany.holderName,
                                rules: [{ required: true, message: '请输入单位名称' }],
                              }
                            )(
                              <Input
                                placeholder="请输入单位名称"
                                maxLength={100}
                                style={{ width: '100%' }}
                              />
                            )}
                          </FormItem>
                        </Col>
                        <Col md={8} sm={24}>
                          <FormItem label="纳税人识别号" {...this.tableSearchLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][taxerIdNo]`,
                              {
                                initialValue: item.invCompany.taxerIdNo,
                                rules: [
                                  {
                                    required: true,
                                    message: '最大长度不超过18位的数字或字母',
                                    pattern: /^[a-zA-Z0-9]{1,18}$/,
                                  },
                                ],
                              }
                            )(<Input placeholder="请输入纳税人识别号" maxLength={19} />)}
                          </FormItem>
                        </Col>
                        <Col md={8} sm={24}>
                          <FormItem label="单位地址" {...this.tableSearchLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][holderAddrs]`,
                              {
                                initialValue: item.invCompany.holderAddrs,
                                rules: [{ required: true, message: '请输入单位地址' }],
                              }
                            )(<Input placeholder="请输入单位地址" maxLength={100} />)}
                          </FormItem>
                        </Col>
                      </Row>
                      <Row>
                        <Col md={8} sm={24}>
                          <FormItem label="电话" {...this.tableSearchLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][phone]`,
                              {
                                initialValue: item.invCompany.phone,
                                rules: [
                                  {
                                    required: true,
                                    message: '固话或手机',
                                    pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/,
                                  },
                                ],
                              }
                            )(<Input placeholder="请输入电话" maxLength={12} />)}
                          </FormItem>
                        </Col>
                        <Col md={8} sm={24}>
                          <FormItem label="开户行" {...this.tableSearchLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][bankOfDepoName]`,
                              {
                                initialValue: item.invCompany.bankOfDepoName,
                                rules: [{ required: true, message: '请输入开户行' }],
                              }
                            )(<Input placeholder="请输入开户行" maxLength={100} />)}
                          </FormItem>
                        </Col>
                        <Col md={8} sm={24}>
                          <FormItem label="银行账号" {...this.tableSearchLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][bankAcco]`,
                              {
                                initialValue: item.invCompany.bankAcco,

                                rules: [
                                  {
                                    required: true,
                                    message: '最大长度不超过25的数字',
                                    pattern: /^\d{1,25}$/,
                                  },
                                ],
                              }
                            )(<Input placeholder="请输入银行账号" maxLength={25} />)}
                          </FormItem>
                        </Col>
                      </Row>
                    </Card>
                    <Card title="发票支付信息">
                      {/* item.invMailList.map((items, index) => renderInvType(item.id, items, index)) */}
                      {renderInvType(item.id, item.invMailList)}
                    </Card>
                  </div>
                ))}
                {!costId && (
                  <Button
                    type="dashed"
                    style={{ width: '100%', height: 50 }}
                    icon={<PlusOutlined />}
                    onClick={this.addInvInfo}
                  >
                    继续添加
                  </Button>
                )}
              </div>
            </Form>
            <FooterToolbar>
              <Button style={{ marginLeft: 8 }} onClick={this.cancel}>
                取消
              </Button>

              <Button
                style={{ marginLeft: 8 }}
                onClick={this.submit}
                type="primary"
                loading={submitLoading}
              >
                提交
              </Button>
            </FooterToolbar>
            <SelectTitleAddr
              modalVisible={modalVisible}
              handleModalVisible={this.handleModalVisible}
              titleAddrType={titleAddrType}
              saveTitleOrAddr={this.saveTitleOrAddr}
              dataSource={titleAddrType === '1' ? invoiceList : mailAddrList}
              selectTitleLoading={selectTitleLoading}
            />
          </div>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default CostCenter;
